<template>
    <div>
      <el-form :model="formData" :rules="rules" ref="formData" label-width="100px">
      <el-form-item label="所属父节点"   prop="parent" >
         <el-select v-model="formData.parent" style="width:660px" clearable placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>   
      <el-form-item label="子节点名字"   prop="childName" >
        <el-input v-model="formData.childName" placeholder="格式:   1-1"></el-input>
      </el-form-item>
      
      <!--视频上传-->
      <el-form-item label="上传视频" prop="discussTitle">
       <el-upload class="avatar-uploader" action="" :accept="acceptType" :http-request="beginUpload" :show-file-list="false">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
         <el-progress :percentage="Number(percentage.toFixed(2))"></el-progress>
   
      </el-form-item>


    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="text" @click="handleClose">重置</el-button>
      <el-button type="primary" @click="handleSubmit"
                 :loading="loading">{{loading?'提交中...':'确认提交'}}</el-button>
    </span>
    </div>
</template>

<script>
  //import {getAllRoleList} from "../../../api/modules/role";
  import {add,selectFather} from "@/api/modules/coursevideo";
  import {getCookie} from '@/libs/cookie'   
  import OSS from 'ali-oss'
  
  var upurl = ''
  export default {
    name: "edit",
    components: {},
     props:{
             // 文件上传的接受的类型  video/* :视频类型， image/*：图片，根据需要判断
            acceptType:{
                type: String,
                default: 'video/*'   
            },
        },
    data() {
      return {
        imageUrl: '',
        percentage: 0,
        checkpoint: null,
        client: null,
        filename: '',
        upurl: '',
        loading: false,
        username:'',

        formData: {
          id:'',
          videoUrl:'',
          courseId:'',
          parent:'',
          childName:'',
          parentName:'',
          name:''
        },
        options:[],
        address:[],
         rules: {
          parent: [
            {required: true, message: "父节点不能为空", trigger: "blur"}
          ],
          childName: [
            {required: true, message: "子节点名不能为空", trigger: "blur"}
          ]
        },
        message:{
          msg1:'设置成功',
          msg2:'视频不能为空',
          msg3:'父节点不能为空',
          msg4:'子节点不能为空'
        },
        rules: {
          childName: [
            {required: true, message: "子节点不能为空", trigger: "blur"}
          ],

        },
        
        refresh: false
      }
    },
    mounted() {
         let courseID = JSON.parse(getCookie("courseID") || '{}');
         this.formData.courseId = courseID.courseID
         this.selectFather()
    },
     created() {
            this.client = new OSS({
                region: 'oss-cn-hangzhou',
                accessKeyId: 'LTAI4GGkWMN9SyN1AkRK6qCT',
                accessKeySecret: 'sQf4RnuvZM47hXV5XxBazZqyXzJyNU',
                bucket: '0628',
                secure: false
            })
        },
    methods: {
      handleClose() {
 
        this.$refs.formData.resetFields()
      },
          async ossUpload(filename, file) {
                let _this = this
                try {
                    let result = await _this.client.multipartUpload(filename, file, {
                        progress: async function (p, checkpoint) {
                            _this.checkpoint = checkpoint
                            _this.percentage = p * 100
                        },
                        checkpoint: _this.checkpoint
                    })
                    console.log(result)
                } catch (e) {
                    console.log(e)
                }
            },
        beginUpload(file) {
          const isWord = ['video/mp4'].includes(file.file.type);
                if(!isWord) this.$message.error('视频必须是video/mp4');
                else{
                let _this = this
                let filename = file.file.name
                filename = filename.split('.')[0] + '_' + new Date().getTime() + '.' + filename.split('.')[1]
                _this.file = file
                _this.filename = filename
                _this.ossUpload(filename, file.file)
                //保存上传的文件下载地址
                upurl = this.client.signatureUrl(_this.filename);
               // console.log(upurl)
                // location.reload();
                }
      },
      selectFather(filter){
        filter = {
          ...filter,
          ...this.formData
        }

        selectFather(filter).then(res =>{
          this.options = res.data.treeFather
        //  console.log(res.data.treeFather)
        })
      },


      handleSubmit() {
        this.$refs.formData.validate(valid => {
          if (valid) {
            this.formData.videoUrl = upurl
            this.formData.parentName = '0'
            this.formData.name = this.formData.childName
           // console.log("formData")
          //  console.log(this.formData)
            this.loading = true
            if(this.formData.parent==''){
              this.toast(this.message.msg3,10)
               this.loading = false
                this.refresh = true
            } 
            else if(this.formData.childName=='') {
              this.toast(this.message.msg4,10)
               this.loading = false
                this.refresh = true
            } 
            else if(this.formData.videoUrl=='') {
              this.toast(this.message.msg2,10)
              this.loading = false
                this.refresh = true
            }
            else{
              add({
                ...this.formData,
              }).then(res => {
                this.loading = false
                if (res.success) {
                  
                  this.toast(res.message)
                  
                }
                this.refresh = true
                this.handleClose()
                location.reload()
              })
            }
           
          }
        })
      }
    }
  }
</script>

<style scoped>

</style>
